package net.lab1024.sa.admin.module.business.supercomputer.sendtask;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.supercomputer.datatask.dao.DatataskDao;
import net.lab1024.sa.admin.module.business.supercomputer.datatask.domain.bo.DatataskBO;
import net.lab1024.sa.admin.module.business.supercomputer.datatask.domain.entity.DatataskEntity;
import net.lab1024.sa.base.module.support.job.core.SmartJob;
import net.lab1024.sa.base.module.support.job.repository.SmartJobDao;
import net.lab1024.sa.base.module.support.job.repository.domain.SmartJobEntity;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeleteScheduled implements SmartJob {
    @Resource
    DatataskDao datataskDao;
    @Resource
    @Lazy
    SmartJobDao smartJobDao;
    @Override
    public String run(String param) {
        // 找到所有启用的任务的id判断时间是否改变,若改变则删除
        ArrayList<Integer> idsEnabled = datataskDao.selectEnabledTask().stream().map(DatataskBO::getTaskId).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        // 找到所有未启用的任务的id进行删除
        ArrayList<Integer> idsUnEnabled = new ArrayList<>(datataskDao.selectAllId());
        idsUnEnabled.removeAll(idsEnabled); // idsUnEnabled 所有不可用的任务id

        //当前定时表中存在的任务
        List<SmartJobEntity> JobList = smartJobDao.getNameAndTimeOnlyTask();

        // 将 idsUnEnabled 转换为 HashSet
        Set<Integer> idsUnEnabledSet = new HashSet<>(idsUnEnabled);

        // 定义正则表达式以提取数字
        Pattern pattern = Pattern.compile("\\((\\d+)\\)");

        // 使用单次遍历来筛选匹配的 IDs 已经禁用的任务的主键
        List<Integer> matchedIds = new ArrayList<>();

        for (SmartJobEntity job : JobList) {
            Matcher matcher = pattern.matcher(job.getJobName());
            if (matcher.find()) {
                Integer jobId = Integer.valueOf(matcher.group(1));
                if (idsUnEnabledSet.contains(jobId)) {
                    matchedIds.add(job.getJobId());
                }
            }
        }

        List<Integer> mismatchedTaskIds = idsEnabled.stream()
                .filter(taskId -> {
                    DatataskEntity datataskEntity = datataskDao.selectById(taskId);
                    if (datataskEntity == null) {
                        return false; // 如果找不到对应的实体，跳过
                    }

                    LocalDateTime taskUpdateTime = datataskEntity.getUpdateTime(); // 获取 task 的 updateTime

                    // 找到 jobList 中与当前 taskId 匹配的 jobName
                    Optional<LocalDateTime> jobUpdateTimeOpt = JobList.stream()
                            .filter(job -> job.getJobName().equals("数据传输任务(" + taskId + ")"))
                            .map(SmartJobEntity::getUpdateTime)
                            .findFirst(); // 找到第一个匹配的 job

                    // 比较 updateTime
                    return jobUpdateTimeOpt.isPresent() && !taskUpdateTime.equals(jobUpdateTimeOpt.get());
                })
                .collect(Collectors.toList());

        // 输出不匹配的 Task IDs
        System.out.println(mismatchedTaskIds);
        //此处为表中存在且任务表中未启用的主键集合
        System.out.println(matchedIds);

        //此处为表中存在且任务表中发生更改的主键集合


        //存删除主键
        ArrayList<Integer> idsDel = new ArrayList<>();
        idsDel.addAll(mismatchedTaskIds);
        idsDel.addAll(matchedIds);

        if(idsDel.isEmpty())
            return "本次清除0个任务";
        //删除
        smartJobDao.deleteBatchIds(idsDel);
        return "本次清除"+idsDel.size()+"个任务";
    }
}
